package per.yhh.xxxtsj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import per.yhh.xxxtsj.entity.Good;
import per.yhh.xxxtsj.entity.PageResult;
import per.yhh.xxxtsj.entity.User;
import per.yhh.xxxtsj.mapper.GoodMapper;
import per.yhh.xxxtsj.service.GoodService;

import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yhh
 * @since 2022-04-10
 */
@Service
public class GoodServiceImpl extends ServiceImpl<GoodMapper, Good> implements GoodService {

    final GoodMapper goodMapper;

    public GoodServiceImpl(GoodMapper goodMapper) {
        this.goodMapper = goodMapper;
    }



    @Override

    public Boolean addGood(Good good) {

        return goodMapper.insert(good) == 1;
    }

    @Override
    public PageResult<Good> getGoodsByPageAndKey(String keyword, Integer num, Integer size) {
        size = Math.min(size, 10);
        num = Math.max(num, 1);
        Page<Good> page = new Page<>(num, size);
        QueryWrapper<Good> queryWrapper = null;
        if (!Objects.equals(keyword, "")) {
            queryWrapper = new QueryWrapper<Good>();
            queryWrapper.like("good_name", keyword)
                    .or()
                    .like("content", keyword)
                    .or()
                    .eq("gid", keyword);
        }
        Page<Good> GoodPage = goodMapper.selectPage(page, queryWrapper);
        return new PageResult<>(GoodPage.getRecords(), GoodPage.getPages());
    }

    @Override
    public PageResult<Good> getGoodsByPageAndKeyAndId(Long uid, String keyword, Integer num, Integer size) {
        size = Math.min(size, 10);
        num = Math.max(num, 1);
        Page<Good> page = new Page<>(num, size);
        QueryWrapper<Good> queryWrapper = new QueryWrapper<Good>();
        queryWrapper.eq("uid", uid);
        if (!Objects.equals(keyword, "")) {
            queryWrapper.like("good_name", keyword)
                    .or()
                    .like("content", keyword)
                    .or()
                    .eq("gid", keyword);
        }
        Page<Good> GoodPage = goodMapper.selectPage(page, queryWrapper);
        return new PageResult<>(GoodPage.getRecords(), GoodPage.getPages());
    }

    @Override
    public Good buy(User user, Integer gid) {
        Good good = goodMapper.selectById(gid);
        if (good.getStock() > 0) {
            good.setStock(good.getStock() - 1);
            goodMapper.updateById(good);
            return good;
        }
        return null;
    }
}
